package com.small.handler;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.log4j.Logger;
import com.small.proxy.Proxy;

/**
 * bean缓存助手类
 * @author 乐乐
 *
 */
public class BeanHelper {
  private static final Logger logger = Logger.getLogger(AopHandler.class);
  
  /**
   * bean缓存
   */
  private static Map<Class<?>, Object> BEAN_MAP = new ConcurrentHashMap<Class<?>, Object>();
  
  
  public static void init() {
    //获取项目下所有Controller  转化为JavaBean
    List<Class<?>> classes = ClassHelper.getControllerListClass();
    for (Class<?> clazz : classes) {
      try {
        BEAN_MAP.put(clazz, clazz.newInstance());
      } catch (InstantiationException e) {
        logger.error(e.toString());
      } catch (IllegalAccessException e) {
        logger.error(e.toString());
      }
    }
    
    //所有切面转为Bean
    List<Class<?>> aspectList = ClassHelper.getAspectListClass();
    for (Class<?> clazz : aspectList) {
      try {
        BEAN_MAP.put(clazz, (Proxy)clazz.newInstance());
      } catch (Exception e) {
        logger.error(e.toString());
      }
    }
    
    //所有默认全局切面转为Bean
    List<Class<?>> globaltList = ClassHelper.getGlobalAspectListClass();
    for (Class<?> clazz : globaltList) {
      try {
        BEAN_MAP.put(clazz, (Proxy)clazz.newInstance());
      } catch (Exception e) {
        logger.error(e.toString());
      }
    }
  }
  
  /**
   * 设置JavaBean
   * @param key
   * @param value
   */
  public static void setBean(Class<?> key, Object value) {
    if (BEAN_MAP.containsKey(key)) {
      BEAN_MAP.remove(key);
    }
    BEAN_MAP.put(key, value);
  }
  
  /**
   * 根据类获取JavaBean
   * @param key
   */
  public static Object getBean(Class<?> key) {
    if (!BEAN_MAP.containsKey(key)) {
      return null;
    }
    return BEAN_MAP.get(key);
  }
  
  /**
   * 获取JavaBean缓存
   */
  public static Map<Class<?>, Object> getBeanMap() {
    return BEAN_MAP;
  }
  
}
